﻿using System;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Threading;

namespace Kotonoha.Client.Synch {

    public class SynchronizationManager {
        public static event Action SynchStart;
        public static event Action SynchEnd;
        private static SynchronizationManager instance;

        private DirectoryInfo dir;

        private bool inSynch;
        private static Timer timer;

        private SynchronizationManager(string s) {
            timer = new Timer(watch, this, 0, 1000);
            dir = new DirectoryInfo(s);
        }

        public static void Start(string dir) {
            if (instance == null) {
                SynchronizationManager manager = new SynchronizationManager(dir);
            }
        }

        private void watch(object state) {
            try {
                doWatch();
            } catch (Exception e) {
                Debug.WriteLine(e.ToString());
            }
        }

        private void doWatch() {
            FileInfo[] begin = dir.GetFiles("synch_token_begin");
            if (begin.Length != 0 && !inSynch) {
                if (SynchStart != null) {
                    SynchStart.Invoke();
                }
                inSynch = true;
                return;
            }

            FileInfo[] end = dir.GetFiles("synch_token_end");
            if (end.Length != 0) {
                if (inSynch && SynchStart != null) {
                    SynchStart.Invoke();
                }
                if (SynchEnd != null) {
                    SynchEnd.Invoke();
                }
                foreach (var info in end) {
                    info.Delete();
                }
                inSynch = false;
            }
        }
    }
}
